package cn.itcast.dao.impl;

import cn.itcast.dao.StudentDao;
import cn.itcast.domain.Student;
import cn.itcast.utils.JdbcUtil;

import java.sql.*;
import java.util.ArrayList;

public class StudentDaoImpl implements StudentDao {
    //核对用户名和密码是否正确
    @Override
    public Student findByStudentnameAndPassword(String username, String password) {
        Connection con = null;
        PreparedStatement stat = null;
        ResultSet rs = null;
        Student stu = new Student();
        try {
            //建立连接
            con = JdbcUtil.getConnection();
            //返回编译对象
            PreparedStatement statement = con.prepareStatement("SELECT * FROM student WHERE username=? AND password=?");
            statement.setString(1, username);
            statement.setString(2, password);
            //执行sql语句
            rs = statement.executeQuery();
            //读取
            if (rs.next()) {  //如果有数据,说明账户密码正确
                Integer db_id = rs.getInt("id");
                String db_username = rs.getString("username");
                String db_password = rs.getString("password");
                stu.setId(db_id);
                stu.setName(db_username);
                stu.setPassword(db_password);
                return stu;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            JdbcUtil.close(con, stat, rs);
        }
        return null;
    }

    //返回所有学生的集合
    @Override
    public ArrayList<Student> findAllStudent() {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        ArrayList<Student> list = new ArrayList<>();
        Student stu;
        try {
            //建立连接
            con = JdbcUtil.getConnection();
            //返回编译对象
            ps = con.prepareStatement("SELECT id,username,password FROM student");
            //运行
            rs = ps.executeQuery();
            while (rs.next()) {
                int id = rs.getInt("id");
                String username = rs.getString("username");
                String password = rs.getString("password");
                stu = new Student(id,username,password);
                list.add(stu);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(con, ps, rs);
        }
        return list;
    }
}
